package com.jsz.yun.ai.field.util.ttl;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuhongru
 * @date 2023/12/15
 * @description 用于将当前线程的本地变量转移至线程池的线程中，需结合{@link TransferableThreadLocal}类共同使用
 */
public class ThreadLocalTransferDecorator {

    public static Runnable decorate(Runnable runnable) {
        return new ThreadLocalTransferRunnable(runnable);
    }

    private static class ThreadLocalTransferRunnable implements Runnable {

        private final Runnable runnable;
        private final Thread mainThread;
        private Map<ThreadLocal, Object> context;

        ThreadLocalTransferRunnable(Runnable runnable) {
            this.runnable = runnable;
            mainThread = Thread.currentThread();
            Map<ThreadLocal<?>, Object> tlMap = TransferableThreadLocal.getTlMap();
            context = new HashMap<>(tlMap);
        }

        private void contextTransfer() {
            context.forEach(ThreadLocal::set);
            context = null;
        }

        @Override
        public void run() {
            contextTransfer();
            try {
                runnable.run();
            } finally {
                TransferableThreadLocal.clear(mainThread);
            }
        }
    }
}
